Background Fetching Indicators
查询的status === 'loading'状态足以显示查询的初始硬加载状态,但有时您可能希望显示查询在后台重新获取的附加指示符。要做到这一点,查询还提供了一个isFetching
布尔值,你可以使用它来显示它处于抓取状态,而不管状态变量的状态:
function Todos() {
const {
status,
data: todos,
error,
isFetching
} = useQuery({
queryKey: ['todos'],
QueryFn: fetchTodos
})
return status === 'loading' ? (
<span>loading...</span>
) : status === 'error' ? (
<span>Error: {error.message}</span>
) : (
<>
{isFetching ? <div>Refreshing</div> : null}
<div>
{todos.map((todo) => (<Todo todo={todo} />))}
</div>
</>
)
}
Displaying Global Background Fetching Loading State
显示全局后台抓取加载状态
除了单独的查询加载状态,如果你想在任何查询正在读取时显示一个全局加载指示器(包括在后台),你可以使用useIsFetching
钩子:
import { useIsFetching } from '@tanstack/react-query'
function GlobalLoadingIndicator() {
const isFetching = useIsFetching()
return isFetching ? (
<div>Queries are fetching in the background...</div>
) : null
}